"""
2.	用python代码底层实现可分离卷积（25分）。已知输入数据和卷积核分别为：
输入数据维度[c,h,w]=[2,5,5]：
[[[1,0,1,2,1],[0,2,1,0,1],[1,1,0,2,0],[2,2,1,1,0],[2,0,1,2,0]],[[2,0,2,1,1],[0,1,0,0,2],[1,0,0,2,1],[1,1,2,1,0],[1,0,1,1,1]]]
卷积核维度[in_c,k,k]=[2,3,3]：[[[ 1, 0, 1],[-1, 1, 0],[ 0,-1, 0]],[[-1, 0, 1],[ 0, 0, 1],[ 1, 1, 1]]]
"""
# ①	导入numpy包、输入数据和卷积核
import numpy as np
from python_ai.CV_5.single_respect.depth_separable_conv._csdn_data import input_data, weights_data

inputs = np.array([[[1, 0, 1, 2, 1], [0, 2, 1, 0, 1], [1, 1, 0, 2, 0], [2, 2, 1, 1, 0], [2, 0, 1, 2, 0]],
                   [[2, 0, 2, 1, 1], [0, 1, 0, 0, 2], [1, 0, 0, 2, 1], [1, 1, 2, 1, 0], [1, 0, 1, 1, 1]]],
                  dtype=np.float32)
weights = np.array([[[1, 0, 1], [-1, 1, 0], [0, -1, 0]], [[-1, 0, 1], [0, 0, 1], [1, 1, 1]]], dtype=np.float32)
inputs = np.array(input_data)
weights = np.array(weights_data)

print('inputs', inputs.shape, inputs.dtype)
print('weights', weights.shape, weights.dtype)


# ②	定义卷积计算函数
def my_conv(inputs, weights):
    h, w = inputs.shape
    k, _ = weights.shape
    padding = k // 2
    padded = np.zeros((h + padding * 2, w + padding * 2), dtype=np.float32)
    padded[padding:h + padding, padding: w + padding] = inputs
    results = np.zeros_like(inputs, dtype=np.float32)
    for row in range(padding, h + padding):
        for col in range(padding, w + padding):
            window = padded[row - padding: row + padding + 1, col - padding: col + padding + 1]
            results[row - padding, col - padding] = (window * weights).sum()
    return results


# ③	定义深度可分离卷积计算函数
def my_depthwise(inputs, weights):
    results = np.zeros_like(inputs, dtype=np.float32)
    for ci in range(inputs.shape[0]):
        results[ci] = my_conv(inputs[ci], weights[ci])
    return results

# ④	定义主函数main（）
def main():
    results = my_depthwise(inputs, weights)
    print(results)


# ⑤	打印输出深度可分离卷积结果
if '__main__' == __name__:
    main()
